import axios from 'axios'
import { MessageBox} from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { message } from '@/utils/resetMessage'

const resMessage = message;

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 36000 // 请求超时
})

service.interceptors.request.use(
  config => {
    const token_type = "Bearer"
    if (store.getters.token) {
      config.headers.Authorization = token_type + ' ' + getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 1) {
      resMessage({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      if (res.code === 10401 || res.code === 10402 || res.code === 10403 || res.code === 10404) {
        MessageBox.confirm(res.msg, '退出登录', {
          confirmButtonText: '重新登录',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      if(res.data && res.data.list==null && typeof(res.data)!='number' && typeof(res.data)!='string'){
        res.data.list=[]
      }
      return res
    }
  },
  error => {
    const { data } = error.response;
    if (data.code === 10401 || data.code === 10402 || data.code === 10403 || data.code === 10404) {
      MessageBox.confirm(data.msg, '退出登录',{
        confirmButtonText: '重新登录',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })
    }else{
      // kol申请直接设置KOL模式
      if(data.msg!='not is kol user'){
        resMessage({
          message: data.msg || '网络不稳定,请再次刷新本页面',
          type: 'error',
          duration: 5 * 1000
        })
      }
    }
    return Promise.reject(data)
  }
)

export default service
